﻿#region 程序集引用
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Web;
#endregion

#region 版权注释
/*===========================================================================
// Copyright (C) 2017 Zhang.cn，并保留所有 
// 作者：吴岸标 QQ:405403610
// 创建日期：2017-09-03
// 功能描述： IP操作
===========================================================================*/
#endregion

namespace Zhang
{
    namespace Utils
    {
        /// <summary>
        ///  IP操作
        /// </summary>
        public static class IP
        {
            /// <summary>
            /// 穿过代理服务器取远程用户真实IP地址
            /// </summary>
            /// <returns></returns>
            public static string GetTrueIP()
            {
                string ip, logContent;
                string[] arrIP;

                ip = string.Empty;
                logContent = "";
                try
                { 
                    if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
                    {
                        if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] == null)
                        {
                            if (HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"] != null)
                            {
                                ip = HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"].ToString();
                            }
                            else
                            {
                                if (HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] != null)
                                {
                                    ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
                                }
                                else
                                {
                                    ip = "202.96.134.133";
                                }
                            }
                        }
                        else
                        {
                            if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString().IndexOf(",") > 0)
                            {
                                arrIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString().Split(',');
                                ip = arrIP[arrIP.Length - 1].Trim();
                            }
                            else
                            {
                                ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
                            }
                        }
                    }
                    else if (HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] != null)
                    {
                        ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
                    }
                    else
                    {
                        ip = "202.96.134.133";
                    }

                    if (ip.Length > 15)//== "116.231.93.23, 61.136.163.246")
                    {
                        logContent += "http_via=" + HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null ? HttpContext.Current.Request.ServerVariables["HTTP_VIA"].ToString() : "";
                        logContent += ";http_x_forwarded_for=" + HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null ? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString() : "";
                        logContent += ";http_client_ip=" + HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"] != null ? HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"].ToString() : "";
                        logContent += ";remote_add=" + HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] != null ? HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString() : "";
                        //Logs.logSave(logContent, "Test001");
                    }
                }
                catch (Exception ex)
                {
                    return "";
                }

                return ip;
            }

            /// <summary>
            /// 获取客户端IP
            /// </summary>
            /// <returns></returns>
            public static string GetClientIP()
            {
                string clientIP = "";

                if (HttpContext.Current != null)
                {
                    clientIP = HttpContext.Current.Request.ServerVariables["HTTP_Cdn-Src-Ip"];

                    if (string.IsNullOrEmpty(clientIP) || clientIP.Trim() == "")
                    {
                        clientIP = HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"];
                    }

                    if (string.IsNullOrEmpty(clientIP) || clientIP.Trim() == "")
                    {
                        clientIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                    }

                    if (string.IsNullOrEmpty(clientIP) || clientIP.Trim() == "")
                    {
                        clientIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                    }
                }

                return clientIP;
            }

            /// <summary>
            /// 根据IP获取城市信息
            /// </summary>
            /// <param name="ip"></param>
            /// <returns></returns>
            public static Model.CityInfo GetCityByIp(string ip)
            {
                WebClient MyWebClient = new WebClient();
                MyWebClient.Credentials = CredentialCache.DefaultCredentials;//获取或设置用于向Internet资源的请求进行身份验证的网络凭据  
                Byte[] pageData = MyWebClient.DownloadData("http://ip.taobao.com/service/getIpInfo.php?ip=" + ip); //从指定网站下载数据  
                string pageHtml = Encoding.Default.GetString(pageData);
                try
                {
                    var result = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Zhang.Model.CityInfoResult>(pageHtml);
                    if (result.Code == 0)
                    {
                        return result.Data;
                    }
                    else
                    {
                        return null;
                    }
                }
                catch
                {
                    return null;
                }
            }


            /// <summary>
            /// 根据ip获取地址信息
            /// </summary>
            /// <param name="ip"></param>
            /// <returns></returns>
            public static string GetAddressByIp(string ip)
            {
                if (ip.Split('.').Length == 4)
                {
                    string str1 = ip.Split('.')[0];
                    string str2 = ip.Split('.')[1];
                    string str3 = ip.Split('.')[2];
                    string str4 = ip.Split('.')[3];
                    long num = long.Parse(str1) * 16777216 + long.Parse(str2) * 65536 + long.Parse(str3) * 256 + long.Parse(str4);
                    Zhang.SQLServer.IPAddress ipAddress = new SQLServer.IPAddress();
                    return ipAddress.GetIpAddress(num.ToString());
                }
                else
                {
                    return "未知";
                }
            }
        }
    }
}
